package com.tricode.ile.training.task.one.quicksort;

public class QuickSortAlghoritm {

	/**
	 * @param array is the array of numbers
	 * @param firstElement is the first element of that array
	 * @param lastElement is the last element of that array
	 */
	public void quickSort(int array[], int firstElement, int lastElement) {
		int tmpFirstElement = firstElement;
		int tmpLastElement = lastElement;
		
		int middleElement = array[(tmpFirstElement + tmpLastElement)/2];
		while(tmpFirstElement < tmpLastElement) {
			while(array[tmpFirstElement] < middleElement) {
				tmpFirstElement++;
			}
			
			while(array[tmpLastElement] > middleElement) {
				tmpLastElement--;
			}
			
			if(tmpFirstElement <= tmpLastElement) {
				swich(array, tmpFirstElement, tmpLastElement);
				tmpFirstElement++;
				tmpLastElement--;
			}
		}
		
		if(firstElement < tmpLastElement) {
			quickSort(array, firstElement, tmpLastElement);
		}
		if(tmpFirstElement < lastElement) {
			quickSort(array, tmpFirstElement, lastElement);
		}
	}

	private void swich(int[] array, int tmpFirstElement, int tmpLastElement) {
		int tmp = array[tmpFirstElement];
		array[tmpFirstElement] = array[tmpLastElement];
		array[tmpLastElement] = tmp;
	}
	
}
